/** ****************************************************************
 * 云云对接联调API, 模拟平台云
 *******************************************************************/
const Request = require('../request')
const dbHelper = require('./utils/dbHelper')
const randomHelper = require('./utils/randomHelper')

const Paths = {}

class CloudConn {
  constructor(client_id, code) {
    this.code = code
    this.initTsp(client_id)
  }

  /**
   * 初始化 tsp 信息: 地址、client_id、secret 等
   * @param appid
   */
  async initTsp(client_id) {
    Object.assign(this, await dbHelper.T_TSPS.query(`client_id = "${client_id}"`), this.initATRT()) // 将tsp查询回来的数据都assign到this上下文中
  }

  /**
   * 1.3.10 Authorization Code
   * 根据 Authorization Code 获取RT/AT
   */
  async initATRT() {
    return await Request.post(`${this.url}/token`,
      {
        grant_type: 'authorization_code',
        code: this.code,
        client_id: this.client_id,
        client_secret: this.client_secret,
        redirect_uri: this.redirect_uri || 'http://www.huawei.com'
      }, { 'Content-Type': 'application/x-www-form-urlencoded' }
    )
  }

  /**
   * 1.3.11 令牌刷新
   */
  refreshToken() {
    return Request.post(`${this.url}/token`,
      {
        grant_type: 'refresh_token',
        client_id: this.client_id,
        client_secret: this.client_secret,
        refresh_token: this.refresh_token
      }, { 'Content-Type': 'application/x-www-form-urlencoded' }
    )
  }

  /**
   * 1.3.1 账号授权
   */
  grant() {
    const body = {
      header: this.builderReqHeader('AcceptGrant'), payload: {
        grant: {
          type: 'OAuth2.AuthorizationCode', // 授权类型
          code: 'VG***ot==' // 用户级鉴权时带给三方用的华为侧的code
        }
      }
    }
    Request.post(`${this.url}/service`, body)
  }

  /**
   * 构造请求header
   */
  builderReqHeader(namespace) {
    return {
      namespace,
      thirdPartyId: this.thirdPartyId,
      granteeId: randomHelper.granteeId(),
      messageId: randomHelper.messageId(),
      timestamp: Date.now()
    }
  }
}
